package logic

import (
	"box-fresh-serv/box_fresh_servrpc/box_fresh_servrpc"
	"box-fresh-serv/box_fresh_servrpc/internal/svc"
	"box-fresh-serv/modles/cache"
	"box-fresh-serv/modles/mysql"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type GoodsShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsShowLogic {
	return &GoodsShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsShowLogic) GoodsShow(in *box_fresh_servrpc.GoodsShowRequest) (*box_fresh_servrpc.GoodsShowResponse, error) {
	// todo: add your logic here and delete this line

	var goods mysql.Goods

	key := fmt.Sprintf("goods_Id+%d", in.GoodsId)
	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if result == "" {

		err := goods.GoodsFindById(mysql.DB, in.GoodsId)
		if err != nil {
			return nil, errors.New("用户Id不存在,查询不到")
		}

		marshal, _ := json.Marshal(goods)
		cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*30)

	} else {
		json.Unmarshal([]byte(result), &goods)
	}

	return &box_fresh_servrpc.GoodsShowResponse{
		GoodsId: int64(goods.ID),
		Title:   goods.Title,
		Price:   float32(goods.Price),
		Stock:   goods.Stock,
		Image:   goods.Image,
	}, nil
}
